package com.yami.shop.common.config;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yami.shop.common.util.RedisUtil;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class SendEmail {

	private static final String TITLE = "";

	@Autowired
	JavaMailSender mailSender;
	
	private static final ExecutorService thread = new ThreadPoolExecutor(1, 10, 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(50));

	@Value("${spring.mail.username}")
	private String from;

	public void send(String subject, String msg, String to) throws Exception {
		if (StringUtils.isEmpty(to)) {
			return;
		}
		if (!StringUtils.isEmpty(RedisUtil.get("count_" + to))) {
			throw new Exception("发送邮件太频繁,请稍后再试!");
		}
		thread.execute(new Runnable() {
			@Override
			public void run() {
				try {
					final MimeMessage mimeMessage = mailSender.createMimeMessage();
					final MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
					message.setFrom(from);
					message.setTo(to);
					message.setSubject(subject);
					message.setText(TITLE + msg);
					mailSender.send(mimeMessage);
					RedisUtil.set("count_" + to, to, 60);
				} catch (Exception e) {
					log.error("发送邮件失败!", e);
				}
			}
		});
	}

}
